package com.tzy.rpc.util;/**
 * @description:
 * @Author HP
 * @create 2022/3/9 21:54
 */

import com.tzy.rpc.entity.RpcRequest;
import com.tzy.rpc.entity.RpcResponse;
import com.tzy.rpc.enumeration.ResponseCode;
import com.tzy.rpc.enumeration.RpcError;
import com.tzy.rpc.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author HP
 * @create 2022-03-09 21:54
 * @desc: 检查响应和请求
 **/
public class RpcMessageChecker {
    private  static final String INTERFACE_NAME="interfaceName";
    private static final Logger logger= LoggerFactory.getLogger(RpcMessageChecker.class);

    private RpcMessageChecker(){

    }

    public static void check(RpcRequest rpcRequest, RpcResponse rpcResponse){
        if (rpcResponse==null){
            logger.error("调用服务失败，serviceName:{}", rpcRequest.getInterfaceName());
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
        }

        //响应与请求的请求号不同
        if (!rpcRequest.getRequestId().equals(rpcResponse.getRequestId())){
            throw new RpcException(RpcError.RESPONSE_NOT_MATCH, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
        }
        //调用失败
        if (rpcResponse.getStatus()==null || !rpcResponse.getStatus().equals(ResponseCode.SUCCESS.getCode())){
            logger.error("调用服务失败，serviceName:{}，RpcResponse:{}", rpcRequest.getInterfaceName(), rpcResponse);
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
        }
    }
}
